﻿namespace Digitalmes.Application.Mes;

/// <summary>
/// 计数器管理对象
/// </summary>
public sealed class CounterService : IApplicationService
{
    private readonly SugarRepository<BasicCounter> _counterRepo;

    public CounterService(SugarRepository<BasicCounter> counterRepo)
    {
        _counterRepo = counterRepo;
    }

    /// <summary>
    /// 生成下一个计数器
    /// </summary>
    /// <param name="classify">流水号分类</param>
    /// <returns></returns>
    public async Task<long> NextAsync(string classify)
    {
        if (string.IsNullOrWhiteSpace(classify))
        {
            return 0;
        }

        long number = 1;
        var counter = await _counterRepo.GetFirstAsync(s => s.Classify == classify);
        if (counter is null)
        {
            counter = new BasicCounter { Classify = classify, Number = number, UpdateTime = DateTime.Now };
            await _counterRepo.InsertAsync(counter);
        }
        else
        {
            number = counter.Number++;
            await _counterRepo.AsUpdateable(counter).UpdateColumns(s => new { s.Number, s.UpdateTime }).ExecuteCommandAsync();
        }

        return number;
    }
}
